"""
(1)	题目描述：
编写程序，实现图像的如下通道运算。
找出两个差异最大的通道，对这两个通道进行相减运算，并进行二值化。
"""
# ①　导入相关头文件
import cv2 as cv
import numpy as np

np.random.seed(1)

# ②　定义相关变量
# ③　读入彩色图像文件
path = '../../../../large_data/pic/leena.jpg'
img = cv.imread(path, cv.IMREAD_COLOR)

# ④　指针方式访问图像数据
# ⑤　计算不同通道的灰度误差
diff_info_arr = []
calculated_pairs = set()
for ch1i in range(3):
    for ch2i in range(3):
        if ch1i == ch2i:
            continue
        ch1, ch2 = ch1i, ch2i
        if ch1 > ch2:
            ch1, ch2 = ch2, ch1
        if (ch1, ch2) in calculated_pairs:
            continue
        calculated_pairs.add((ch1, ch2))
        diff = np.mean((img[:, :, ch1] - img[:, :, ch2]) ** 2)
        diff_info_arr.append((diff, (ch1, ch2)))

# ⑥　计算误差最大的两个通道的差图像
diff_info_arr_sorted = sorted(diff_info_arr, key=lambda x: x[0], reverse=True)
max_diff_pair = diff_info_arr_sorted[0][1]
diff = img[:, :, max_diff_pair[0]] - img[:, :, max_diff_pair[1]]

# ⑦　输出差图像
cv.imshow('diff', diff)

# ⑧　二值化差图像
ret, bin = cv.threshold(diff, 200, 255, cv.THRESH_BINARY_INV)
cv.imshow('bin', bin)

# ⑨　在二值图像上绘制轮廓
# 11　对不同轮廓进行不同颜色的填充
# 12　输出颜色填充图像
contours, hierarchy = cv.findContours(bin, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
bg = np.zeros_like(img)


def rand_color():
    return (
        np.random.randint(0, 256),
        np.random.randint(0, 256),
        np.random.randint(0, 256),
    )


for c in contours:
    cv.drawContours(bg, [c], 0, rand_color())
cv.imshow('contours', bg)

# Finally
cv.waitKey(0)
cv.destroyAllWindows()
